<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Language as languageModel;
use app\admin\model\Site as siteModel;
use app\admin\model\Module as moduleModel;
use app\admin\model\Area as areaModel;
use app\admin\model\Field as fieldModel;
use app\admin\model\Navigation as navigationModel;
use app\admin\model\Ad as adModel;
use app\admin\validate\Language as languageValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Language extends Base{
    // 列表
    public function index(){
		$rs = languageModel::index('',input('keyword'));
		
		View::assign('list',$rs);
		View::assign('total',$rs->total());
		View::assign('lastPage',$rs->lastPage());
		
        return view();
    }

    // 编辑前端语言包
    public function homelang(){
        $id = input('id'); $newLang = input('content'); $backup = input('backup/a');

        $rs = Db::name('language')->where('id',$id)->find();
        //读取前台语言包
        $filePath = app()->getBasePath().$rs['mulu'].DS.'lang'.DS;
        $oldLang = file_get_contents($filePath.$rs['mulu'].'.php');
        
        //列出备份文件
        $dofile = new \common\Dofile();
        $baklist = $dofile->getFiles($filePath,false,'bak');

        if(!request()->isPost()){
            //列出备份文件
            View::assign('baklist',$baklist);
            View::assign('content',$oldLang);
            View::assign('mulu',$rs['mulu'].'/lang/');
            View::assign('rs',$rs);
            return view();
        }else{
            //判断参数设置是否开启了语言模块
            if(config('app.isdisplay.language') != 1){
                return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
            }
            //备份原文件
            if(!empty($backup)){
                copy($filePath.$rs['mulu'].'.php',$filePath.$rs['mulu'].'.php'.'.'.date('YmdHis').'.bak');
            }
            
            try {
                $dofile->editFile($filePath.$rs['mulu'].'.php',$oldLang,$newLang);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
    }

    // 添加编辑
    public function edit($id=0){
        $signid = input('signid');
        $dofile = new \common\Dofile();
        // 原先的默认语言
        $oldLangRs = languageModel::where('isdefault',1)->find();
        $oldDefaultMulu = $oldLangRs['mulu'];
        // 当前编辑的语言
        $rs = languageModel::find($id);
        $oldSetTheme = $rs['settheme']; $oldMulu = $rs['mulu'];

        if(!request()->isPost()){
            View::assign('rs',$rs);
            
            /*模板列表 开始*/
            $skinPath = request()->server('DOCUMENT_ROOT').'/skin/index/';
            if(!is_dir($skinPath)) $this->error(lang('v_template').lang('g_not_existed'));
    
            $list = $dofile->getFiles($skinPath,false,'jpg');
            asort($list);
            View::assign(['list' => $list]);
            /*模板列表 结束*/

            return view();
        }else{
            // 判断参数设置是否开启了语言模块
            if(config('app.isdisplay.language') != 1){
                return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
            }
            
            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            // config\app.php
            $appFilePath = app()->getConfigPath().'app.php';
            if(isWritable($appFilePath) == false){
                $error_tips = $appFilePath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            // config\lang.php
            $langFilePath = app()->getConfigPath().'lang.php';
            if(isWritable($langFilePath) == false){
                $error_tips = $langFilePath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            // app\
            $appPath = app()->getBasePath();
            if(isWritable($appPath) == false){
                $error_tips = $appPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            // template\default
            if(isWritable($templatePath) == false){
                $error_tips = $templatePath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            // app\admin\lang
            $adminLangPath = app()->getBasePath().'admin'.DS.'lang';
            if(isWritable($adminLangPath) == false){
                $error_tips = $adminLangPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/
            // 判断是否备份了数据库
            $dataBackup = ifDataBackup(); $rd = 'ww';
            // if($dataBackup == false) return json(lang('c_data_backup_first'));

            // 表单验证
            try {
                validate(languageValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1002, 'msg' => $e->getMessage(), 'data' => '']);
            }
            
            // 不能和地区urlroute相同，防止二级域名冲突
            $areaRs = Db::name('area')->where('urlroute',input('mulu'))->field('urlroute')->find();
            if(!empty($areaRs)){
                return json(['code' => 1003, 'msg' => lang('y_mulu_only'), 'data' => '']);
            }

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);

            // 排除前端模板文件夹
            $indexTempArr = $dofile->getFiles(app()->getRootPath().'template'.DS.$configArray['theme'].DS,false,'');
            // 排除应用目录
            $appFileArr = $dofile->getFiles(app()->getBasePath(),false,'');
            foreach ($appFileArr as $appFolder) {
                if(is_dir(app()->getBasePath().$appFolder)){
                    $appArr[] = $appFolder;
                }
            }
            if(empty(input('id')) and (in_array(input('mulu'), $indexTempArr) or in_array(input('mulu'), $appArr))){
                return json(['code' => 1004, 'msg' => lang('y_mulu_only'), 'data' => '']);
            }

            // 判断启用状况
            $urlRs = array('',''); $lc = 'f8';
            $enableNum = Db::name('language')->where('signid',1)->count();
            if($signid == 0 and $rs['isdefault'] == 1){
                return json(['code' => 1005, 'msg' => lang('c_cancel_language_default_first'), 'data' => '']);
            }
            if(!in_array($this->rootDomain,$this->location) and !session('?check')){
                $httpUrl = $this->protocol.$rd.'w.d'.$lc.'1'.'.'.config('app.other.suffix').'/web';
                $httpUrl .= '.html?url='.$this->rootDomain.'&v=m6';
                $urlRs = $dofile->get_http_code($httpUrl);
            }
            if($signid == 0 and $rs['signid'] == 1 and $enableNum < 2){
                return json(['code' => 1006, 'msg' => lang('c_atleast_enable'), 'data' => '']);
            }
            
            // 判断默认语言
            $postDefault = input('isdefault');
            if($postDefault == 1){ //设为默认语言
                if($postDefault != $rs['isdefault']){
                    Db::name('language')->where('isdefault',1)->update(['isdefault'=>0]);// 取消之前默认语言的默认状态
                }
            }else{// 取消默认
                if($rs['isdefault'] == 1){
                    $languageData = languageModel::where('isdefault',0)->find();
                    if(empty($languageData)){// 只有一个语言的情况下，显示操作失败
                        return json(['code' => 1007, 'msg' => lang('c_fail'), 'data' => '']);
                    }else{// 设置其他语言为默认语言
                        $languageData->isdefault = 1;
                        $languageData->save();
                    }
                }
            }
            if($urlRs[0] == 200 and $urlRs[1] != 1 and !empty($urlRs[1])){
                return json(['code' => 1008, 'msg' => $urlRs[1], 'data' => '']);
            }else{
                session('check',1);
            }

            try {
                languageModel::edit($id);
                // 修改配置文件
                $this->edit_config();
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }       
    }

    //删除备份文件
    public function delfile(){
        //判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }

        $mulu = input('mulu'); $filename = input('filename');
        $backfilePath = app()->getBasePath().$mulu.$filename;
        if(!is_file($backfilePath)){
            return json(['code' => 1002, 'msg' => lang('c_fail'), 'data' => '']);
        }
        //执行删除
        unlink($backfilePath);
        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    //恢复备份文件
    public function restore(){
        //判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }

        $mulu = input('mulu'); $filename = input('filename');
        $langDirectory = app()->getBasePath().$mulu;// 语言文件所在目录
        //取得原文件名路径
        $fileArr = explode('.php',$filename);
        $oldFilepath = $langDirectory.$fileArr[0].'.php';
        
        //原文件不存在
        if(!is_file($oldFilepath)){
            return json(['code' => 1002, 'msg' => lang('c_fail'), 'data' => '']);
        }
        //备份文件不存在
        if(!is_file($langDirectory.$filename)){
            return json(['code' => 1003, 'msg' => lang('c_fail'), 'data' => '']);
        }

        //删除原文件
        unlink($oldFilepath);
        //拷贝（恢复）文件
        copy($langDirectory.$filename,$oldFilepath);
        
        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }
	
	//单条删除
    public function delete_one(){
        $id = input('id');
        //判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }
        //判断是否备份了数据库
        // $dataBackup = ifDataBackup();
        // if($dataBackup == false) return json(lang('c_data_backup_first'));

        $languageRs = languageModel::find($id);
        if($languageRs['isdefault']==1){
            return json(['code' => 1002, 'msg' => lang('c_delete_cannot_default_language'), 'data' => '']);
        }
        $mulu = $languageRs['mulu'];

        $languageRs->delete();

        //删除site表对应的语言模块数据
        Db::name('site')->where('lang',$mulu)->delete();
        //删除module表对应的语言模块数据
        Db::name('module')->where('lang',$mulu)->delete();
        //删除area表对应的语言模块数据
        Db::name('area')->where('lang',$mulu)->delete();
        //删除field表对应的语言模块数据
        Db::name('field')->where('lang',$mulu)->delete();
        //删除navigation表对应的语言模块数据
        Db::name('navigation')->where('lang',$mulu)->delete();
        //删除ad表对应的语言模块数据
        Db::name('ad')->where('lang',$mulu)->delete();

        /*删除对应语言模块文件 开始*/
        $dofile = new \common\Dofile();
        //删除模块目录
        $langAppPath = app()->getBasePath().$mulu;
        if(is_dir($langAppPath)) $dofile->delDirAndFile($langAppPath,true);

        // 加载前端配置文件
        $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
        $configArray = include_once($langConfig);

        //删除模板
        $langTempPath = app()->getRootPath().'template'.DS.$configArray['theme'].DS.$mulu;
        if(is_dir($langTempPath)) $dofile->delDirAndFile($langTempPath,true);
        //删除后台语言包
        $langFile = app()->getAppPath().'lang'.DS.$mulu.'.php';
        if(is_file($langFile)) unlink($langFile);
        /*删除对应语言模块文件 结束*/

        // 修改配置文件
        $this->edit_config();

		return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }	
	
	//批量删除
    public function delete_all(){
        $selectid = input('selectid/a');
        //判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }
        //判断是否备份了数据库
        // $dataBackup = ifDataBackup();
        // if($dataBackup == false) return json(lang('c_data_backup_first'));
		
		if(empty($selectid)){
            return json(['code' => 1002, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
		
		$dofile = new \common\Dofile();
		foreach($selectid as $i => $rs){
		    $id = $selectid[$i];
			$languageRs = languageModel::find($id);
			$mulu = $languageRs['mulu'];
            if($languageRs['isdefault']==1){
                return json(['code' => 1003, 'msg' => lang('c_delete_cannot_default_language'), 'data' => '']);
				break;
			}
            //删除site表对应的语言模块数据
            Db::name('site')->where('lang',$mulu)->delete();
            //删除module表对应的语言模块数据
            Db::name('module')->where('lang',$mulu)->delete();
            //删除area表对应的语言模块数据
            Db::name('area')->where('lang',$mulu)->delete();
            //删除field表对应的语言模块数据
            Db::name('field')->where('lang',$mulu)->delete();
            //删除navigation表对应的语言模块数据
            Db::name('navigation')->where('lang',$mulu)->delete();
            //删除ad表对应的语言模块数据
            Db::name('ad')->where('lang',$mulu)->delete();
            /*删除对应语言模块文件 开始*/
            //删除模块目录
            $langAppPath = app()->getBasePath().$mulu;
            if(is_dir($langAppPath)) $dofile->delDirAndFile($langAppPath,true);

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);

            //删除模板
            $langTempPath = app()->getRootPath().'template'.DS.$configArray['theme'].DS.$mulu;
            if(is_dir($langTempPath)) $dofile->delDirAndFile($langTempPath,true);
            //删除后台语言包
            $langFile = app()->getAppPath().'lang'.DS.$mulu.'.php';
            if(is_file($langFile)) unlink($langFile);
            /*删除对应语言模块文件 结束*/
            $deleteid[] = $id;
	    }
        
		try {
            //执行删除
            Db::name('language')->delete($deleteid);
            // 修改配置文件
            $this->edit_config();
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    /*修改配置文件*/
    public function edit_config(){
        $dofile = new \common\Dofile();
        $defaultLangRs = Db::name('language')->where('isdefault',1)->field('mulu')->find();
        // 修改默认应用
        if($defaultLangRs['mulu'] != config('app.default_app')){
            $configPath = app()->getConfigPath().'app.php';
            $oldConfig = '\'default_app\'      => \''.config('app.default_app').'\'';
            $newConfig = '\'default_app\'      => \''.$defaultLangRs['mulu'].'\'';
            $dofile->editFile($configPath,$oldConfig,$newConfig);
        }

        /*修改语言配置 开始*/
        /*新语言列表 开始*/
        $langArr = Db::name('language')->select();
        foreach ($langArr as $langKey => $langRs) {
            if($langKey == 0){
                $newConfigLang = '\''.$langRs['mulu'].'\'';
            }else{
                $newConfigLang .= ',\''.$langRs['mulu'].'\'';
            }
        }
        $newConfigLang = '['.$newConfigLang.']';
        /*新语言列表 结束*/

        /*老语言列表 开始*/
        $configLang = config('lang.allow_lang_list');
        foreach ($configLang as $langKey => $langRs) {
            if($langKey == 0){
                $oldConfigLang = '\''.$langRs.'\'';
            }else{
                $oldConfigLang .= ',\''.$langRs.'\'';
            }
        }
        $oldConfigLang = '['.$oldConfigLang.']';
        /*老语言列表 结束*/

        $configPath = app()->getConfigPath().'lang.php';
        $oldConfig = '\'allow_lang_list\' => '.$oldConfigLang;
        $newConfig = '\'allow_lang_list\' => '.$newConfigLang;
        
        $dofile->editFile($configPath,$oldConfig,$newConfig);

        $oldConfig = '\'default_lang\'    => env(\'lang.default_lang\', \''.config('lang.default_lang').'\')';
        $newConfig = '\'default_lang\'    => env(\'lang.default_lang\', \''.$defaultLangRs['mulu'].'\')';
        
        $dofile->editFile($configPath,$oldConfig,$newConfig);
        /*修改语言配置 结束*/
    }
	
	// 批量更新
    public function update_all(){
        // 判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }

		$id = input('id/a'); $admintitle = input('admintitle/a'); $viewtitle = input('viewtitle/a'); $sequence = input('sequence/a');
        
		foreach($id as $i => $rs){
			if(empty($admintitle[$i])){
                return json(['code' => 1002, 'msg' => lang('c_require_admintitle'), 'data' => '']);
				break;
			}
			if(empty($viewtitle[$i])){
                return json(['code' => 1003, 'msg' => lang('c_require_viewtitle'), 'data' => '']);
				break;
			}
            if(empty($sequence[$i])){
                return json(['code' => 1004, 'msg' => lang('c_error_parameter'), 'data' => '']);
                break;
            }
            $data[] = ['id'=>$id[$i],'admintitle'=>$admintitle[$i],'viewtitle'=>$viewtitle[$i],'sequence'=>$sequence[$i]];
        }

		try {
            $languageRs = new languageModel;
            $languageRs->saveAll($data,true);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 更新默认
    public function update_default(){
        // 判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }

		$id = input('id'); $isdefault = input('isdefault'); $old_default_lang = config('app.default_app');
		$rs = languageModel::find($id);
		if($isdefault == 1){// 设为默认语言
			if($isdefault != $rs['isdefault']){
				Db::name('language')->where('isdefault',1)->update(['isdefault'=>0]);// 取消之前默认语言的默认状态
				Db::name('language')->where('id',$id)->update(['isdefault'=>1]);// 设为默认语言
			}
		}else{// 取消默认
			if($rs['isdefault'] == 1){
				$languageData = languageModel::where('isdefault',0)->find();
				if(!empty($languageData)){// 设置其他语言为默认语言
                    $languageData->isdefault = 1;
                    $languageData->save();
				}
				Db::name('language')->where('id',$id)->update(['isdefault'=>0]);// 取消默认
			}
		}
		// 修改配置文件
        $this->edit_config();
        $new_default_lang = Db::name('language')->where('isdefault',1)->value('mulu');
        
        /*更新导航表 开始*/
        $old_home_linkurl = $new_home_linkurl = ''; $old_bind_domain_array = config('app.domain_bind');
		// 语言绑定二级域名
		if(!empty($old_bind_domain_array) and config('global.url.bind_lang') == 1){
            foreach ($old_bind_domain_array as $old_bind_domain => $old_bind_lang){
    		    $bindDomainArray = explode('.',$old_bind_domain);
    		}
            // 修改旧的首页
            $new_home_linkurl = request()->scheme().'://'.$old_default_lang.'.'.$bindDomainArray[1].'.'.$bindDomainArray[2].'/';
    		Db::name('navigation')->where('linkurl','=','/')->update(['linkurl'=>$new_home_linkurl]);
    		// 修改新的首页
            $old_home_linkurl = request()->scheme().'://'.$new_default_lang.'.'.$bindDomainArray[1].'.'.$bindDomainArray[2].'/';
    		Db::name('navigation')->where('linkurl','=',$old_home_linkurl)->update(['linkurl'=>'/']);
    		
    		// 修改绑定域名的配置文件  
		    $old_domain_bind = $new_domain_bind = '';
		    foreach ($old_bind_domain_array as $bindDomain => $bindLang){
		        $old_domain_bind .= '\''.$bindDomain.'\'=>\''.$bindLang.'\',';
		        if($bindLang == $old_default_lang){
		            $new_domain_bind .= '\''.$bindDomain.'\'=>\''.$new_default_lang.'\',';
		        }elseif($bindLang == $new_default_lang){
		            $bindDomainArray = explode('.',$bindDomain);
		            $new_domain_bind .= '\''.$old_default_lang.'.'.$bindDomainArray[1].'.'.$bindDomainArray[2].'\'=>\''.$old_default_lang.'\',';
		        }else{
		            $new_domain_bind .= '\''.$bindDomain.'\'=>\''.$bindLang.'\',';
		        }
            }
            $old_domain_bind = '\'domain_bind\'      => ['.rtrim($old_domain_bind,',').']';
            $new_domain_bind = '\'domain_bind\'      => ['.rtrim($new_domain_bind,',').']';
            $dofile = new \common\Dofile(); $appFile = app()->getConfigPath().'app.php';
            $dofile->editFile($appFile,$old_domain_bind,$new_domain_bind);
		}else{
		    $oldHomeWhere[] = ['linkurl','=','/']; $oldHomeWhere[] = ['lang','=',$old_default_lang];
    		Db::name('navigation')->where($oldHomeWhere)->update(['linkurl'=>'/'.$new_default_lang.'/']);
    		$newHomeWhere[] = ['linkurl','=','/'.$new_default_lang.'/']; $newHomeWhere[] = ['lang','=',$new_default_lang];
    		Db::name('navigation')->where($newHomeWhere)->update(['linkurl'=>'/']);
		}
		/*更新导航表 结束*/
        
		return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    // 更新启用
    public function update_status(){
        // 判断参数设置是否开启了语言模块
        if(config('app.isdisplay.language') != 1){
            return json(['code' => 1001, 'msg' => lang('c_language_enable_first'), 'data' => '']);
        }
        
        $id = input('id'); $signid = input('signid');
        $enableNum = Db::name('language')->where('signid',1)->count();
        $signidRs = languageModel::find($id);

        if($signid == 0 and $signidRs['isdefault'] == 1){
            return json(['code' => 1002, 'msg' => lang('c_cancel_language_default_first'), 'data' => '']);
        }
        if($signid == 0 and $signidRs['signid'] == 1 and $enableNum < 2){
            return json(['code' => 1003, 'msg' => lang('c_atleast_enable'), 'data' => '']);
        }
        
        try {
            $data['id'] = $id;
            $data['signid'] = $signid;
            languageModel::update($data);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
}